//
//  RDReaderDelegateController.m
//  readApp
//
//  Created by 飞猪 on 2018/8/16.
//  Copyright © 2018年 😝😝😝😝😝. All rights reserved.
//

#import "RDReaderDelegateController.h"
#import "RDReader.h"
#import "RDTopSettingView.h"
#import "RDBottomSettingView.h"
#import "RDNetworkTool.h"
#import "RDChapterModel.h"
#import "RDSettingView.h"

@interface RDReaderDelegateController ()
<
RDTopSettingViewDelegate,
RDBottomSettingViewDelegate,
UITableViewDelegate,
UITableViewDataSource,
UIGestureRecognizerDelegate,
RDSettingViewDelegate
>

@property (nonatomic, strong) UIView *containerView;

@property (nonatomic, strong) UIView *sideBar;

@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) NSMutableDictionary<NSString *, NSMutableDictionary<NSString *, NSArray<NSNumber *> *> *> *marksArray;

@property (nonatomic, copy  ) NSString *curBookName;

@property (nonatomic, strong) NSArray<RDNETChapterListModel *> *models;

@property (nonatomic, strong) RDChapterModel *curChapterModel;

@property (nonatomic, weak  ) RDBottomSettingView *bottomSettingView;

@property (nonatomic, weak  ) RDTopSettingView *topSettingView;


@property (nonatomic, weak  ) UITableView *tableView;
@property (nonatomic, weak  ) UIButton *dirBtn;
@property (nonatomic, weak  ) UIButton *markBtn;

@end

@implementation RDReaderDelegateController

- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma mark - Lazyload
- (NSMutableArray *)dataSource {
  if (!_dataSource) {
    _dataSource = [NSMutableArray array];
  }
  return _dataSource;
}

#pragma mark - RDTopSettingViewDelegate
- (void)topSettingView:(RDTopSettingView *)topSettingView clickedIndex:(TopSettingClickType)clickType {
  switch (clickType) {
    case TopSettingClickTypeReadOver: {
      NSLog(@"退出阅读器");
      [self dismissViewControllerAnimated:YES completion:nil];
      [self.containerView removeFromSuperview];
    }
      break;
    case TopSettingClickTypeMarked: {
      NSLog(@"书签操作");
      
      BOOL res = topSettingView.addMarkBtn.selected;
      
      NSString *file = [NSString stringWithFormat:@"%@&%@&%@&%@&%@", self.curChapterModel.bookId, self.curChapterModel.chId, self.curChapterModel.curPage, self.curChapterModel.curPageIntro, self.curChapterModel.chName];
      
      if (!res) {
        // 取消书签
        NSArray *arr = [NSArray arrayWithContentsOfFile:[self cachePath]];
        if (arr) {
          
          if ([arr containsObject:file]) {
            NSMutableArray *tempA = [NSMutableArray arrayWithArray:arr];
            
            [tempA removeObject:file];
            
            [tempA writeToFile:[self cachePath] atomically:YES];
          }
          
        }
      }
      else {
        // 获取当前的 章节 和 页数
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
          
          NSArray *arr = [NSArray arrayWithContentsOfFile:[self cachePath]];
          NSMutableArray *tempA = nil;
          if (arr) {
            
            if (![arr containsObject:file]) {
              tempA = [NSMutableArray arrayWithArray:arr];
              
              [tempA addObject:file];
              
              [tempA writeToFile:[self cachePath] atomically:YES];
            }
            
          }
          else {
            tempA = [NSMutableArray array];
            [tempA addObject:file];
            
            [tempA writeToFile:[self cachePath] atomically:YES];
          }
          
        });
      }
      
    }
      break;
      
    default:
      break;
  }
}

#pragma mark - RDTopSettingViewDelegateEvent
//- (NSString *)totalPath:(RDChapterModel *)model {
//
//  BOOL res = [[NSFileManager defaultManager] fileExistsAtPath:[self cachePath]];
//  if (!res) {
//    NSError *err = nil;
//    BOOL res = [[NSFileManager defaultManager] createDirectoryAtPath:[self cachePath] withIntermediateDirectories:YES attributes:nil error:&err];
//
//    if (res && !err) {
//      //
//      NSString *fileName = [NSString stringWithFormat:@"%@/Caches", [self cachePath]];
//
//      return fileName;
//    }
//
//    return @"";
//  }
//  else {
//    NSString *fileName = [NSString stringWithFormat:@"%@/Caches", [self cachePath]]; // bookid_chid_curPage
//
//    return fileName;
//  }
//
//}

// 书签
- (NSString *)cachePath {
  NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  NSString *docPath = [docDirPath stringByAppendingPathComponent:@"RDCache"];
  return docPath;
}

#pragma mark - RDBottomSettingViewDelegate
- (void)bottomSettingView:(RDBottomSettingView *)bottomSettingView clickedIndex:(BottomSettingClickType)clickType {
  
  switch (clickType) {
    case BottomSettingClickTypeCatalogue: {
      NSLog(@"目录点击");
      [SVProgressHUD showWithStatus:@"加载中..."];
      [SVProgressHUD setFont:[UIFont boldSystemFontOfSize:14.f]];
      [SVProgressHUD setForegroundColor:[UIColor grayColor]];
      [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
      [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
      [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative];
      NSDictionary *params = @{
                               @"chId": self.curChapterModel.chId,
                               @"bookId": self.curChapterModel.bookId
                               };
      [RDNetworkTool requestForChapterList:params successBlock:^(NSArray<RDNETChapterListModel *> *models) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
          [SVProgressHUD dismiss];
          self.models = models;
          [self showCategory];
        });
      } failBlock:^(NSString *errorMsg) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:errorMsg];
      }];
    }
      break;
    case BottomSettingClickTypeDayOrNight: {
      NSLog(@"日夜调整");
      BOOL res = CGColorEqualToColor(self.reader.config.charColor.CGColor, KDayColor.CGColor);
      if (res) {
        self.reader.config.charColor = KNightColor;
        self.reader.config.readerBGImage = [UIImage imageWithColor:[UIColor blackColor]];
      }
      else {
        self.reader.config.charColor = KDayColor;
        self.reader.config.readerBGImage = [UIImage imageNamed:@"yellow"];
      }
    }
      break;
    case BottomSettingClickTypePreChapter: {
      NSLog(@"上一章");
      if ([self.curChapterModel.preChId isEqualToString:@"0"]) break;
      //      [self.reader readChapterAtChapterIndex:self.curChapterModel.preChId pageIndex:1];
      [self.reader readChapterAtChapterIndex:self.curChapterModel pageIndex:1];
    }
      break;
    case BottomSettingClickTypeNextChapter: {
      NSLog(@"下一章");
      if ([self.curChapterModel.nextChId isEqualToString:@"0"]) break;
      //      [self.reader readChapterAtChapterIndex:self.curChapterModel.nextChId pageIndex:1];
      [self.reader readChapterAtChapterIndex:self.curChapterModel pageIndex:1];
    }
      break;
    case BottomSettingClickTypeSetting: {
      NSLog(@"设置");
      [self showSettingView];
    }
      break;
      
    default:
      break;
  }
  
}

#pragma mark - RDBottomSettingViewDelegateEvent
// 目录导航
- (void)showCategory {
  
  [self.containerView removeFromSuperview];
  
  //  if (!self.sideBar) {
  self.sideBar = [[UIView alloc] initWithFrame:CGRectMake(-kScreenWidth, 0, kScreenWidth, kScreenHeight)];
  
  UIView *bgView = [UIView new];
  bgView.backgroundColor = UIColorHex(333333);
  [self.sideBar addSubview:bgView];
  bgView.frame = CGRectMake(0, 0, CGRectGetWidth(self.sideBar.frame) * 0.9, CGRectGetHeight(self.sideBar.frame));
  
  UIButton *dirBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  self.dirBtn = dirBtn;
  dirBtn.frame = CGRectMake(0, [self isFringeScreen] ? 44 : 0, CGRectGetWidth(bgView.frame) * 0.5, 44);
  UIButton *markBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  self.markBtn = markBtn;
  markBtn.frame = CGRectMake(CGRectGetMaxX(dirBtn.frame), CGRectGetMinY(dirBtn.frame), CGRectGetWidth(dirBtn.frame), CGRectGetHeight(dirBtn.frame));
  
  [dirBtn setTitle:@"目录" forState:0];
  dirBtn.backgroundColor = bgView.backgroundColor;
  dirBtn.titleLabel.font = [UIFont systemFontOfSize:14.f];
  [dirBtn setTitleColor:[UIColor whiteColor] forState:0];
  [dirBtn setTitleColor:KGreenColor forState:UIControlStateSelected];
  [dirBtn addTarget:self action:@selector(onDirBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
  [dirBtn setSelected:YES];
  
  [markBtn setTitle:@"书签" forState:0];
  markBtn.backgroundColor = bgView.backgroundColor;
  markBtn.titleLabel.font = dirBtn.titleLabel.font;
  [markBtn setTitleColor:[UIColor whiteColor] forState:0];
  [markBtn setTitleColor:KGreenColor forState:UIControlStateSelected];
  [markBtn addTarget:self action:@selector(onMarkBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
  
  UIView *lineH = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(dirBtn.frame), CGRectGetWidth(dirBtn.frame) * 2, 0.5)];
  UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(dirBtn.frame), CGRectGetMinY(dirBtn.frame), 0.5, CGRectGetHeight(dirBtn.frame))];
  lineV.backgroundColor = [UIColor whiteColor];
  lineH.backgroundColor = [UIColor whiteColor];
  
  UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(dirBtn.frame), CGRectGetWidth(dirBtn.frame) * 2, self.sideBar.height - CGRectGetMaxY(dirBtn.frame) - ([self isFringeScreen] ? 34 : 0)) style:UITableViewStylePlain];
  self.tableView = tableView;
  tableView.showsVerticalScrollIndicator = NO;
  tableView.dataSource = self;
  tableView.delegate = self;
  tableView.backgroundColor = bgView.backgroundColor;
  tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  [self onDirBtnClicked:dirBtn];
  
  UIWindow *window = [[UIApplication sharedApplication].delegate window];
  [window addSubview:self.sideBar];
  [self.sideBar addSubview:dirBtn];
  [self.sideBar addSubview:markBtn];
  [self.sideBar addSubview:tableView];
  [self.sideBar addSubview:lineH];
  [self.sideBar addSubview:lineV];
  
  UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onSideViewClicked:)];
  tap.delegate = self;
  [self.sideBar addGestureRecognizer:tap];
  //  }
  
  [UIView animateWithDuration:0.2 animations:^{
    self.sideBar.transform = CGAffineTransformMakeTranslation(kScreenWidth, 0);
  } completion:^(BOOL finished) {
    
  }];
  
}

// 目录点击
- (void)onDirBtnClicked:(UIButton *)btn {
  
  // 处理数据源
  [self.dataSource removeAllObjects];
  for (RDNETChapterListModel *model in self.models) {
    [self.dataSource addObject:model];
  }
  
  btn.selected = YES;
  self.markBtn.selected = NO;
  
  [self.tableView reloadData];
  
  //
  for (RDNETChapterListModel *model in self.dataSource) {
    if ([model.chId isEqualToString:self.curChapterModel.chId]) {
      [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.dataSource indexOfObject:model] inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
      break;
    }
  }
  
}


// 书签点击
- (void)onMarkBtnClicked:(UIButton *)btn {
  
  NSArray *arr = [NSArray arrayWithContentsOfFile:[self cachePath]];
  // 处理数据源
  [self.dataSource removeAllObjects];
  for (NSString *str in arr) {
    NSArray *strings = [str componentsSeparatedByString:@"&"];
    
    if (![self.curChapterModel.bookId isEqualToString:strings[0]]) {
      continue;
    }
    
    RDChapterModel *chapterModel = [[RDChapterModel alloc] init];
    chapterModel.bookId = strings[0];
    chapterModel.chId = strings[1];
    chapterModel.curPage = strings[2];
    chapterModel.curPageIntro = strings[3];
    chapterModel.chName = strings[4];
    
    [self.dataSource addObject:chapterModel];
  }
  
  btn.selected = YES;
  self.dirBtn.selected = NO;
  
  [self.tableView reloadData];
  
  //
  BOOL isTop = YES;
  for (RDChapterModel *model in self.dataSource) {
    if ([model.bookId isEqualToString:self.curChapterModel.bookId] && [model.chId isEqualToString:self.curChapterModel.chId] && [model.curPage isEqualToString:self.curChapterModel.curPage]) {
      [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.dataSource indexOfObject:model] inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
      isTop = NO;
      break;
    }
  }
  
  if (isTop) {
    [self.tableView scrollToTop];
  }
  
}


- (void)onSideViewClicked:(UITapGestureRecognizer *)ges {
  
  [UIView animateWithDuration:0.2 animations:^{
    self.sideBar.frame = CGRectMake(-kScreenWidth, 0, kScreenWidth, kScreenHeight);
  } completion:^(BOOL finished) {
    [self.sideBar removeFromSuperview];
  }];
  
}

- (void)showSettingView {
  [self.bottomSettingView removeFromSuperview];
  
  RDSettingView *settingView = [[[NSBundle mainBundle] loadNibNamed:@"RDSettingView" owner:nil options:nil] firstObject];
  settingView.delegate = self;
  if ([self isFringeScreen]) {
    settingView.frame = CGRectMake(0, kScreenHeight, self.view.bounds.size.width, 176);
  }
  else {
    settingView.frame = CGRectMake(0, kScreenHeight, self.view.bounds.size.width, 142);
  }
  
  [self.containerView addSubview:settingView];
  
  // 字体
  NSString *fontName = self.reader.config.fontName;
  if ([fontName isEqualToString:@"KaiTi"]) {
    settingView.kaiti.selected = YES;
    settingView.sender = settingView.kaiti;
  }
  else if ([fontName isEqualToString:@"SimSun"]) {
    settingView.simsun.selected = YES;
    settingView.sender = settingView.simsun;
  }
  else{
    settingView.system.selected = YES;
    settingView.sender = settingView.system;
  }
  
  // 亮度
  NSNumber *bright = [[NSUserDefaults standardUserDefaults] objectForKey:@"Brightness"];
  if (bright) {
    CGFloat brightValue = [bright floatValue];
    
    if (brightValue >= 0 && brightValue <= 1) {
      settingView.slider.value = brightValue;
      [[UIScreen mainScreen] setBrightness:brightValue];
    }
    else {
      settingView.slider.value = [UIScreen mainScreen].brightness;
      [[UIScreen mainScreen] setBrightness:[UIScreen mainScreen].brightness];
    }
  }
  else {
    settingView.slider.value = [UIScreen mainScreen].brightness;
    [[UIScreen mainScreen] setBrightness:[UIScreen mainScreen].brightness];
  }
  
  // 背景颜色
  NSString *imgStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"readerBGImage"];
  
  if (imgStr && imgStr.length > 0) {
    NSInteger index = [settingView.colors indexOfObject:imgStr];
    settingView.bgColor = [settingView.buttons objectForKey:@(index)];
    settingView.bgColor.selected = YES;
  }
  else {
    settingView.bgColor = [settingView.buttons objectForKey:@(2)];
    settingView.bgColor.selected = YES;
  }
  
  [UIView animateWithDuration:0.2 delay:0 usingSpringWithDamping:1.0 initialSpringVelocity:3 options:UIViewAnimationOptionCurveLinear animations:^{
    settingView.transform = CGAffineTransformMakeTranslation(0, -settingView.height);
  } completion:^(BOOL finished) {
    
  }];
}

#pragma mark - RDSettingViewDelegate
- (void)settingView:(RDSettingView *)bottomSettingView clickedIndex:(RDSettingClickType)clickType value:(id)value {
  
  switch (clickType) {
    case RDSettingClickTypeFont: {
      NSLog(@"设置字体");
      const NSInteger val = [value integerValue];
      if (val == 1) {
        self.reader.config.fontName = nil;
      }
      else if (val == 2) {
        self.reader.config.fontName = @"KaiTi";
      }
      else if (val == 3) {
        self.reader.config.fontName = @"SimSun";
      }
      else{
        self.reader.config.fontName = nil;
      }
      
      [[NSUserDefaults standardUserDefaults] setObject:self.reader.config.fontName forKey:@"fontName"];
      [[NSUserDefaults standardUserDefaults] synchronize];
    }
      break;
    case RDSettingClickTypeColor: {
      NSLog(@"设置背景颜色");
      NSString *color = (NSString *)value;
      BOOL res = [color isEqualToString:@"A39470"];
      if (res) {
        self.reader.config.readerBGImage = [UIImage imageNamed:@"yellow"];
      }
      else {
        NSInteger index = [bottomSettingView.colors indexOfObject:color];
        self.reader.config.readerBGImage = [UIImage imageWithColor:bottomSettingView.hexColors[index]];
      }
      
      [[NSUserDefaults standardUserDefaults] setObject:color forKey:@"readerBGImage"];
      [[NSUserDefaults standardUserDefaults] synchronize];
    }
      break;
    case BottomSettingClickTypePreChapter: {
      NSLog(@"上一章");
      
      
    }
      break;
    case BottomSettingClickTypeNextChapter: {
      NSLog(@"下一章");
      
      
    }
      break;
      
    default:
      break;
  }
}

- (BOOL)isFringeScreen {
  if(@available(iOS 11.0, *)) {
   return !UIEdgeInsetsEqualToEdgeInsets([UIApplication sharedApplication].windows.firstObject.safeAreaInsets, UIEdgeInsetsZero);
  }
  else {
    return NO;
  }
}


#pragma mark - RDReaderDelegate
- (void)readerSettingClicked:(RDReader *)reader chapterModel:(RDChapterModel *)chapterModel {
  self.curChapterModel = chapterModel;
  
  // 顶部
  RDTopSettingView *topSettingView = [[[NSBundle mainBundle] loadNibNamed:@"RDTopSettingView" owner:nil options:nil] firstObject];
  self.topSettingView = topSettingView;
  topSettingView.delegate = self;
  topSettingView.titleLab.text = chapterModel.chName;
  
  NSArray *arr = [NSArray arrayWithContentsOfFile:[self cachePath]];
  // 处理数据源
  [self.dataSource removeAllObjects];
  for (NSString *str in arr) {
    NSArray *strings = [str componentsSeparatedByString:@"&"];
    
    if ([self.curChapterModel.bookId isEqualToString:strings[0]] && [self.curChapterModel.chId isEqualToString:strings[1]]  && [self.curChapterModel.curPage isEqualToString:strings[2]]) {
      topSettingView.addMarkBtn.selected = YES;
      break;
    }
  }
  
  // 底部
  RDBottomSettingView *bottomSettingView = [[[NSBundle mainBundle] loadNibNamed:@"RDBottomSettingView" owner:nil options:nil] firstObject];
  self.bottomSettingView = bottomSettingView;
  bottomSettingView.slider.maximumValue = self.curChapterModel.totalPage;
  bottomSettingView.slider.minimumValue = 1;
  [bottomSettingView.slider setValue:[self.curChapterModel.curPage integerValue] animated:NO];
  [bottomSettingView.slider addTarget:self action:@selector(sliderClicked:) forControlEvents:UIControlEventValueChanged];
  bottomSettingView.delegate = self;
  
  if ([self isFringeScreen]) {
    topSettingView.frame = CGRectMake(0, -88, self.view.bounds.size.width, 88);
    bottomSettingView.frame = CGRectMake(0, kScreenHeight, self.view.bounds.size.width, 143);
  }
  else {
    topSettingView.frame = CGRectMake(0, -64, self.view.bounds.size.width, 64);
    bottomSettingView.frame = CGRectMake(0, kScreenHeight, self.view.bounds.size.width, 109);
  }
  
  // 容器
  UIView *containerView = [[UIView alloc] initWithFrame:self.view.bounds];
  self.containerView = containerView;
  [containerView addSubview:topSettingView];
  [containerView addSubview:bottomSettingView];
  [containerView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(settingViewClicked:)]];
  
  // 添加到 window
  [KMainWindow addSubview:containerView];
  [UIView animateWithDuration:0.2 delay:0 usingSpringWithDamping:1.0 initialSpringVelocity:3 options:UIViewAnimationOptionCurveLinear animations:^{
    topSettingView.transform = CGAffineTransformMakeTranslation(0, topSettingView.height);
    bottomSettingView.transform = CGAffineTransformMakeTranslation(0, -bottomSettingView.height);
  } completion:^(BOOL finished) {
    
  }];
  
}

- (void)reader:(RDReader *)reader state:(RDReaderState)state {
  
  switch (state) {
    case RDReaderStateBusy: {
      //      if (![SVProgressHUD isVisible]) {
      //        [SVProgressHUD showWithStatus:@"正在读取内容，请稍等..."];
      //        [SVProgressHUD setFont:[UIFont boldSystemFontOfSize:16.f]];
      //        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
      //      }
    }
      break;
    case RDReaderStateReady: {
      //      if ([SVProgressHUD isVisible]) {
      //        [SVProgressHUD dismiss];
      //      }
    }
      break;
      
    default:
      break;
  }
  
}

- (void)reader:(RDReader *)reader chapterTitle:(NSString *)chapterTitle {
  if (chapterTitle && chapterTitle.length > 0 && self.topSettingView) {
    self.topSettingView.titleLab.text = chapterTitle;
  }
}

- (void)reader:(RDReader *)reader chapter:(RDChapterModel *)chapter {
  if (chapter) {
    self.curChapterModel = chapter;
    
    //      切换章节成功要给个回调
    if (self.bottomSettingView) {
      self.bottomSettingView.slider.maximumValue = self.curChapterModel.totalPage;
      self.bottomSettingView.slider.minimumValue = 1;
      [self.bottomSettingView.slider setValue:0 animated:YES];
    }
  }
}

- (void)reader:(RDReader *)reader curChapter:(NSString *)curChapter curPage:(NSInteger)curPage totalPages:(NSInteger)totalPages curPageContent:(NSString *)content {
  
  self.curChapterModel.curPage = [@(curPage) stringValue];
  self.curChapterModel.curPageIntro = content;
  
}

#pragma mark - RDReaderDelegateEvent
- (void)sliderClicked:(ASValueTrackingSlider *)slider {
  static NSInteger pageCount = 1;
  
  NSInteger page = (NSInteger)(slider.value + 0.5);
  
  [self.reader readChapterAtChapterIndex:self.curChapterModel pageIndex:page];
  //  [self.reader readChapterAtChapterIndex:self.curChapterModel.chId pageIndex:page];
  
  if (pageCount != page) {
    NSArray *arr = [NSArray arrayWithContentsOfFile:[self cachePath]];
    for (NSString *str in arr) {
      NSArray *strings = [str componentsSeparatedByString:@"&"];
      if ([self.curChapterModel.bookId isEqualToString:strings[0]] && [self.curChapterModel.chId isEqualToString:strings[1]]  && [[@(page) stringValue] isEqualToString:strings[2]]) {
        self.topSettingView.addMarkBtn.selected = YES;
        break;
      }
      else {
        self.topSettingView.addMarkBtn.selected = NO;
      }
    }
  }
  
  pageCount = page;
  
}

- (void)settingViewClicked:(UITapGestureRecognizer *)ges {
  UIView *containerView = ges.view;
  RDTopSettingView *topSettingView = [containerView.subviews firstObject];
  RDBottomSettingView *bottomSettingView = [containerView.subviews lastObject];
  
  CGPoint gesPoint = [ges locationInView:containerView];
  CGRect validRect = CGRectMake(0, topSettingView.height, kScreenWidth, kScreenHeight - topSettingView.height - bottomSettingView.height);
  
  if (CGRectContainsPoint(validRect, gesPoint)) {
    [UIView animateWithDuration:0.2 delay:0 usingSpringWithDamping:1 initialSpringVelocity:6 options:UIViewAnimationOptionCurveLinear animations:^{
      topSettingView.transform = CGAffineTransformIdentity;
      bottomSettingView.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
      [containerView removeFromSuperview];
    }];
  }
  
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
  if (self.dirBtn.selected && !self.markBtn.selected) {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reader.demo.Dircell"];
    if (!cell) {
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reader.demo.Dircell"];
      cell.contentView.backgroundColor = [UIColor clearColor];
      cell.backgroundColor = [UIColor clearColor];
    }
    
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:14.f];
    [cell.contentView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
      make.edges.mas_equalTo(UIEdgeInsetsMake(0, 20, 0, 20));
    }];
    RDNETChapterListModel *model = [self.dataSource objectAtIndex:indexPath.row];
    label.text = model.chName;
    if ([model.chId isEqualToString:self.curChapterModel.chId]) {
      label.textColor = KGreenColor;
    }
    else {
      label.textColor = [UIColor whiteColor];
    }
    
    UIView *line = [UIView new];
    line.backgroundColor = UIColorHex(555555);
    [cell.contentView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
      make.left.mas_equalTo(label);
      make.bottom.mas_equalTo(0);
      make.right.mas_equalTo(-18);
      make.height.mas_equalTo(0.5);
    }];
    
    return cell;
  }
  else {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reader.demo.Markcell"];
    if (!cell) {
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reader.demo.Markcell"];
      cell.contentView.backgroundColor = [UIColor clearColor];
      cell.backgroundColor = [UIColor clearColor];
    }
    
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:12.f];
    [cell.contentView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
      make.left.mas_equalTo(20);
      make.top.mas_equalTo(8);
      make.width.mas_lessThanOrEqualTo(cell.contentView.mas_width).offset(-100);
    }];
    RDChapterModel *model = [self.dataSource objectAtIndex:indexPath.row];
    label.text = model.chName;
    if ([model.chId isEqualToString:self.curChapterModel.chId] && [model.curPage isEqualToString:self.curChapterModel.curPage]) {
      label.textColor = KGreenColor;
    }
    else {
      label.textColor = [UIColor whiteColor];
    }
    
    UILabel *detaillabel = [[UILabel alloc] init];
    detaillabel.font = [UIFont systemFontOfSize:12.f];
    detaillabel.numberOfLines = 0;
    [cell.contentView addSubview:detaillabel];
    [detaillabel mas_makeConstraints:^(MASConstraintMaker *make) {
      make.left.mas_equalTo(label);
      make.top.mas_equalTo(label.mas_bottom).offset(6);
      make.bottom.mas_equalTo(-8);
      make.width.mas_lessThanOrEqualTo(cell.contentView.mas_width).offset(-40);
    }];
    detaillabel.text = model.curPageIntro;
    if ([model.chId isEqualToString:self.curChapterModel.chId] && [model.curPage isEqualToString:self.curChapterModel.curPage]) {
      detaillabel.textColor = KGreenColor;
    }
    else {
      detaillabel.textColor = [UIColor whiteColor];
    }
    
    UIView *line = [UIView new];
    line.backgroundColor = UIColorHex(555555);
    [cell.contentView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
      make.left.mas_equalTo(label);
      make.bottom.mas_equalTo(0);
      make.right.mas_equalTo(-18);
      make.height.mas_equalTo(0.5);
    }];
    
    return cell;
  }
  
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  
  if (self.dirBtn.selected && !self.markBtn.selected) {
    [self onSideViewClicked:nil];
    
    RDNETChapterListModel *model = [self.dataSource objectAtIndex:indexPath.row];
    //    [self.reader readChapterAtChapterIndex:model.chId pageIndex:1];
    
    RDChapterModel *chapterModel = [[RDChapterModel alloc] init];
    chapterModel.chId = model.chId;
    chapterModel.preChId = model.preChId;
    chapterModel.preChCharge = model.preChCharge;
    chapterModel.nextChId = model.nextChId;
    chapterModel.nextChCharge = model.nextChCharge;
    [self.reader readChapterAtChapterIndex:chapterModel pageIndex:1];
    
  }
  else {
    [self onSideViewClicked:nil];
    
    RDChapterModel *model = [self.dataSource objectAtIndex:indexPath.row];
    //    [self.reader readChapterAtChapterIndex:model.chId pageIndex:[model.curPage integerValue]];
    [self.reader readChapterAtChapterIndex:model pageIndex:[model.curPage integerValue]];
  }
  
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  if (self.dirBtn.selected && !self.markBtn.selected) {
    return 44.f;
  }
  else {
    return 76.f;
  }
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
  CGPoint point = [gestureRecognizer locationInView:self.sideBar];
  CGRect rect = CGRectMake(0, 0, self.sideBar.width * 0.9, self.sideBar.height);
  if (CGRectContainsPoint(rect, point)) {
    return NO;
  }
  return YES;
}

@end
